package com.yowasa.xiuxian.engine.message.map;

import cn.hutool.core.lang.WeightRandom;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Lists;
import com.yowasa.xiuxian.annoations.CMD;
import com.yowasa.xiuxian.engine.BattleEngine;
import com.yowasa.xiuxian.engine.CommonEngine;
import com.yowasa.xiuxian.engine.HoneEngine;
import com.yowasa.xiuxian.engine.hone.MentalInterface;
import com.yowasa.xiuxian.engine.item.ItemInterface;
import com.yowasa.xiuxian.engine.message.CmdMessageHandler;
import com.yowasa.xiuxian.entity.bo.battle.BattleContent;
import com.yowasa.xiuxian.entity.bo.enemy.EnemyBO;
import com.yowasa.xiuxian.entity.bo.item.UserItemBo;
import com.yowasa.xiuxian.entity.bo.user.UserBO;
import com.yowasa.xiuxian.entity.enums.CmdScopeEnum;
import com.yowasa.xiuxian.entity.mys.SendMessage;
import com.yowasa.xiuxian.entity.po.XiuxianMapEnemyPO;
import com.yowasa.xiuxian.entity.po.XiuxianNpcTab;
import com.yowasa.xiuxian.entity.po.XiuxianTaskTab;
import com.yowasa.xiuxian.entity.po.XiuxianUserTask;
import com.yowasa.xiuxian.exception.HandlerException;
import com.yowasa.xiuxian.service.helper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

@CMD(name = "/地图", scope = CmdScopeEnum.ALL)
public class MapHandler extends CmdMessageHandler {
    @Autowired
    private UserHelper userHelper;
    @Autowired
    private MessageHelper messageHelper;
    @Autowired
    private TaskHelper taskHelper;
    @Autowired
    private ItemHelper itemHelper;
    @Autowired
    private BattleEngine battleEngine;
    @Autowired
    private BattleHelper battleHelper;

    @Override
    public void execute(SendMessage message) {
        UserBO userBO = userHelper.checkOpUserAll(message);
        List<String> params = getAllParam(message);//获取名称
        List<XiuxianNpcTab> path = taskHelper.getAllNpc(userBO.getLocal());

        if (StringUtils.isEmpty(params.get(0))) {
            messageHelper.replyMys(message, "可追加二级指令 交互 开采 收集，当前支持交互，开采\n");
            return;
        }
        if ("交互".equals(params.get(0))) {
            try {
                if (params.size() < 2){
                    throw new HandlerException("请输入你要交互的NPC,这里存在NPC：\n" + path.stream().map(e -> e.getNpcName()).collect(Collectors.joining("\n")));
                }
                String param = params.get(1);
                List<XiuxianNpcTab> collect = path.stream().filter(e -> e.getNpcName().equals(param)).collect(Collectors.toList());
                if (collect.size() == 0){
                    //不存在
                    throw new HandlerException("这里不存在这样的NPC");
                }else {
                    XiuxianNpcTab xiuxianNpcTab = collect.get(0);
                    XiuxianUserTask task = taskHelper.getNowTakByUserId(userBO.getId());
                    if(task == null || !xiuxianNpcTab.getId().equals(task.getXiuxianTaskTab().getNpcId())){
                        if(xiuxianNpcTab.getType() == 2){
                            throw new HandlerException("不是你的任务NPC，不可交互");
                        }
                        String text = commonReply(xiuxianNpcTab);
                        messageHelper.replyMys(message,text);
                    }else {
                        String text = taskReply(xiuxianNpcTab,task.getXiuxianTaskTab(),userBO);
                        messageHelper.replyMys(message,text);
                    }

                }
            }catch (HandlerException e){
                throw e;
            }catch (Exception e){
                throw new HandlerException("出现了一些意料之外的错误 T~T");
            }
        }
        if ("开采".equals(params.get(0))) {
            Map<String,Integer> map = new HashMap<>();
            List<WeightRandom.WeightObj<String>> list = new ArrayList<WeightRandom.WeightObj<String>>();
            ArrayList<String> mineralList = Lists.newArrayList("玄铁矿*30*10", "白铁矿*25*8", "水晶矿*20*8", "魔晶矿*15*4", "紫晶矿*10*2");
            mineralList.forEach(e -> {
                String[] split = e.split("\\*");
                Integer odds = Integer.parseInt(split[1]);
                Integer num = Integer.parseInt(split[2]);
                map.put(split[0],num);
                list.add(new WeightRandom.WeightObj<>(split[0],odds));
            });
            StringBuilder sb = new StringBuilder();
            sb.append("你获得了：\n");
            String s1 = itemHelper.addMineral(list, map, userBO);
            String s2 = itemHelper.addMineral(list, map, userBO);
            sb.append(s1).append("\n").append(s2);
            Integer num = RandomUtil.randomInt(userBO.getStage()) + 1;
            ItemInterface itemInterface = CommonEngine.ITEM_MAP.get("萃凝晶");
            itemHelper.addItem(userBO,itemInterface,num);
            sb.append("\n萃凝晶*").append(num);
            if(Math.random() < 0.13){
                String itemName = "";
                if(userBO.getLocal() <= 9){
                    itemName = "夜泊石";
                }else if(userBO.getLocal() <= 17) {
                    itemName = "石珀";
                }
                ItemInterface specialItemInterface = CommonEngine.ITEM_MAP.get(itemName);
                int i = RandomUtil.randomInt(2) + 1;
                itemHelper.addItem(userBO,specialItemInterface, i);
                sb.append("\n").append(itemName).append("*").append(i);
            }
            userHelper.lockUser(userBO, 30, userBO.getName() + "正在挖矿");
            userHelper.saveUserInfo(userBO);
            messageHelper.replyMys(message,sb.toString());
        }

    }

    private String taskReply(XiuxianNpcTab xiuxianNpcTab, XiuxianTaskTab task, UserBO userBO) throws NoSuchFieldException, IllegalAccessException {
        switch (task.getType()) {
            case 1:
                //交谈
                taskHelper.updateTaskStage(task, userBO);
                return task.getText();
            case 2:
                //提交材料
                String name = task.getName();
                Integer num = task.getNum();
                UserItemBo myItem = itemHelper.getMyItem(userBO.getId(), name);
                if (myItem == null || myItem.getItemNum() < num) {
                    return "东西收集足够了再来找我吧";
                } else {
                    taskHelper.updateTaskStage(task, userBO);
                    return task.getText();
                }
            case 3:
                //击杀怪物
                String emName = task.getName();
                Integer level = task.getNum();
                //构建怪物对象
                EnemyBO enemyBO = genDungeonEnemy(level, emName);
                UserBO enemy = enemyBO.getUserBO();
                //战斗
                BattleContent content = battleEngine.battle(userBO, enemy);
                battleHelper.syncUserState(content);
                if (content.getResult() == 1) {
                    taskHelper.updateTaskStage(task, userBO);
                }
                String join = String.join("\n", content.getMsgLog());
                String s = join + "\n" + task.getText();
                return s;
            case 4:
                String getName = task.getName();
                Integer getNum = task.getNum();
                itemHelper.addItem(userBO, getName, getNum);
                taskHelper.updateTaskStage(task, userBO);
                return task.getText();
            default:
                return commonReply(xiuxianNpcTab);
        }
    }

    public EnemyBO genDungeonEnemy(int num,String name) {
        XiuxianMapEnemyPO enemyPO = new XiuxianMapEnemyPO();
        enemyPO.setEnemyName(name);
        enemyPO.setEnemyMental("修仙野史");
        enemyPO.setEnemyStrategy(name);
        enemyPO.setEnemyStage(num);
        enemyPO.setMsg("");
        UserBO bo = userHelper.initUser(enemyPO.getEnemyName());
        bo.setAge(com.yowasa.xiuxian.util.RandomUtil.randomInt(30, 400));
        bo.getUserConfig().setMental(enemyPO.getEnemyMental());
        MentalInterface mental = HoneEngine.mentalMap.get(bo.getUserConfig().getMental());
        for (int j = 1; j < enemyPO.getEnemyStage(); j++) {
            bo.setLevel(100);
            mental.breakUp(bo);
            userHelper.rebuildBattleInfo(bo);
            bo.buildBaseInfo();
        }

        if (org.apache.commons.lang3.StringUtils.isNotEmpty(enemyPO.getEnemyStrategy())) {
            bo.getUserConfig().getBattleStrategyList().addAll(Arrays.asList(enemyPO.getEnemyStrategy().split(",").clone()));
        }
        userHelper.rebuildBattleInfo(bo);
        EnemyBO enemyBO = new EnemyBO();
        BeanUtils.copyProperties(enemyPO, enemyBO);
        enemyBO.setUserBO(bo);
        return enemyBO;
    }

    private String commonReply(XiuxianNpcTab xiuxianNpcTab) throws NoSuchFieldException, IllegalAccessException {
        int i = RandomUtil.randomInt(3) + 1;
        String name = "text" + i;
        Class<XiuxianNpcTab> xiuxianNpcTabClass = XiuxianNpcTab.class;
        Field declaredField = xiuxianNpcTabClass.getDeclaredField(name);
        declaredField.setAccessible(true);
        Object text = declaredField.get(xiuxianNpcTab);
        return text.toString();
    }


    public String desc(){
        return new StringBuffer().append("与地图上的NPC交互\n")
                .toString();

    }

}
